﻿using System;
using System.Web;
using System.IO;
using System.Collections.Generic;

namespace Regnemaskinen
{
    public class Calculate : IHttpHandler
    {
        /// <summary>
        /// You will need to configure this handler in the web.config file of your 
        /// web and register it with IIS before being able to use it. For more information
        /// see the following link: http://go.microsoft.com/?linkid=8101007
        /// </summary>
        #region IHttpHandler Members

        public bool IsReusable
        {
            // Return false in case your Managed Handler cannot be reused for another request.
            // Usually this would be false in case you have some state information preserved per request.
            get { return true; }
        }

        public void ProcessRequest(HttpContext context)
        {
            //write your handler implementation here.
        }

        #endregion

        bool IHttpHandler.IsReusable
        {
            get { return false; }
        }
        public Calculate()
        {
        }
        void IHttpHandler.ProcessRequest(HttpContext context)
        {
            //throw new NotImplementedException();
            context.Response.Write("<H1>Resultat:</H1>");

            TextReader reader = new StreamReader(context.Request.InputStream);
            //Dictionary<string, string> requestParams = JsonConvert.DeserializeObject<Dictionary<string, string>>(reader.ReadToEnd());
            string op = context.Request.Form["op"];
            decimal lhs = Convert.ToDecimal(context.Request.Form["lhs"]);
            decimal rhs = Convert.ToDecimal(context.Request.Form["rhs"]);
            decimal result = 0.0M;

            switch (op)
            {
                case "/":
                    result = lhs / rhs;
                    break;
                case "*":
                    result = lhs * rhs;
                    break;
                case "-":
                    result = lhs - rhs;
                    break;
                case "+":
                    result = lhs + rhs;
                    break;
            }

            context.Response.Write("<p>" + result.ToString() + "</p>");

            if (context.Request.RequestType == "POST")
            {
                //context.Response.Write("<p>" + reader.ReadToEnd() + "</p>");
                //context.Response.Write("<p>" + s + "</p>");
            }
            else
            {
                // Request was sent incorrectly somehow
            }
            //virker også
            context.Response.Write("<p>" + reader.ReadToEnd() + "</p>");
        }
    }
}
